package io.github.lee.jel.ui.detail

import android.app.Application
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseViewModel
import io.github.lee.core.vm.err.DataParseFailedException
import io.github.lee.core.vm.err.ViewModelException
import io.github.lee.repository.jel.data.session
import io.github.lee.repository.jel.domain.Item
import io.github.lee.repository.jel.repo.ItemRepository
import javax.inject.Inject

@HiltViewModel
class ItemDetailVM @Inject constructor(
    application: Application,
    private val repo: ItemRepository
) : BaseViewModel(application) {

    val detailLiveData = MutableLiveData<Item?>()


    fun itemDetail(itemId: String?) {
        val value = detailLiveData.value
        if (null != value) {
            detailLiveData.postValue(value)
            success()
            return
        }

        val userId = mContext.session?.userId
        launchResult(
            block = { repo.itemDetail(userId, itemId) },
            error = { error(it) }
        ) {
            if (!it.isSuccess) {
                error(ViewModelException(it.code, it.msg))
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                error(DataParseFailedException(mContext))
                return@launchResult
            }
            detailLiveData.postValue(data)
            success()
        }
    }


}